package com.hancx.controller;

import com.hancx.dao.MenuRepository;
import com.hancx.dto.MenuInfoDTO;
import com.hancx.entity.MenuInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping(value = "/menu")
public class MenuController {

    @Autowired
    private MenuRepository menuRepository;

    @RequestMapping("/")
    public ModelAndView index(ModelAndView mav){
        mav.setViewName("system/menuinfo");
        return mav;
    }

    @RequestMapping(value = "/getMenuTree")
    @ResponseBody
    public List getMenuTree(){
        List<MenuInfoDTO> menuList = new ArrayList();
        List<MenuInfo> parents = menuRepository.findByParentIsNull(new Sort(Sort.Direction.ASC, "orderNum"));
        for (MenuInfo menuinfo: parents) {
            List<MenuInfo> children = getChildren(menuinfo.getId());

            MenuInfoDTO dto = new MenuInfoDTO(menuinfo, children);
            menuList.add(dto);
        }
        return menuList;
    }

    public List<MenuInfo> getChildren(Integer id){
        return menuRepository.findByParent(id, new Sort(Sort.Direction.ASC, "orderNum"));
    }

    @GetMapping(value = "/list")
    @ResponseBody
    public Page<MenuInfo> list(@RequestParam(value = "page", defaultValue = "1") Integer page,  //从第0页开始查
                               @RequestParam(value = "limit", defaultValue = "15") Integer limit,  //每页展示几个
                               @RequestParam(value = "sorts", defaultValue = "id") String sorts){  //排序的字段

        Sort sort = new Sort(Sort.Direction.ASC, sorts);
        Pageable pageable = new PageRequest(page - 1, limit, sort);
        Page<MenuInfo> pages = menuRepository.findAll(pageable);
        return pages;
    }
}
